package com.sangzc.orc;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.util.Base64Util;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;

public class Sample {
    //设置APPID/AK/SK
    public static final String APP_ID = "16197539";
    public static final String API_KEY = "9wXFmLhQEVLNBjWwMjVozInn";
    public static final String SECRET_KEY = "Ue2hMYfjTDO3FhhCz9YArN7IEVawEsdS";

    private static final String INVOICE="C:\\Users\\Administrator.JTTLL-F0IR20S\\Desktop\\orcInvoice\\Invoice\\\\{}.jpg";
    private static final String INVOICE_JSON="C:\\Users\\Administrator.JTTLL-F0IR20S\\Desktop\\orcInvoice\\InvoiceJson\\\\{}.json";

    public static void main(String[] args) {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
        //client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
        //client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 可选：设置log4j日志输出格式，若不设置，则使用默认配置
        // 也可以直接通过jvm启动参数设置此环境变量
        //System.setProperty("aip.log4j.conf", "path/to/your/log4j.properties");

        // 调用接口
        List<File> paths = FileUtil.loopFiles("E:\\发票照片");
        for (File path:
             paths) {
            byte[] image = FileUtil.readBytes(path);
            JSONObject res = client.vatInvoice(image, new HashMap<String, String>());
            System.out.println(res.toString());
            JSONObject words_result = res.getJSONObject("words_result");
            String invoiceNum = words_result.getString("InvoiceNum");
            System.out.println(invoiceNum);//发票号码
            FileUtil.writeString(res.toString(),StrUtil.format(Sample.INVOICE_JSON,invoiceNum),Charset.forName("UTF-8"));
            FileUtil.writeBytes(image,StrUtil.format(Sample.INVOICE,invoiceNum));
        }

    }
}
